package com.hontech.dapapp.utils


import android.app.Activity
import android.content.Context

import android.content.pm.PackageManager

import android.view.inputmethod.InputMethodManager
import com.hontech.dapapp.app.AppContext
import java.io.PrintWriter
import java.net.NetworkInterface


const val APP_ID = "com.hontech.dapapp"

fun hideSoftKey(activity: Activity) {
    val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    if (!imm.isActive) {
        return
    }
    val view = activity.currentFocus ?: return
    imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}


fun installApk2(path: String) {
    val rt = Runtime.getRuntime()
        .exec("su")

    val pw = PrintWriter(rt.outputStream)
    pw.println("pm install -r -t $path")
    pw.flush()
    pw.close()
    val v = rt.waitFor()

    if (v != 0) {
        throw IllegalStateException("没有root权限 安装失败")
    }
}


private fun rootGrantPermission(name: String) {
    val runtime = Runtime.getRuntime()
        .exec("su")

    val pw = PrintWriter(runtime.outputStream)
    pw.write("pm grant $APP_ID $name")
    pw.flush()
    pw.close()
    val v = runtime.waitFor()
    if (v != 0) {
        throw IllegalStateException("没有root权限 无法获取${name}")
    }
}

private fun checkPermission(name: String): Boolean {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
        return true
    }
    val ret = AppContext.checkSelfPermission(name)
    return ret == PackageManager.PERMISSION_GRANTED
}


fun stringById(id: Int) = AppContext.resources.getString(id)
fun stringsById(id: Int) = AppContext.resources.getStringArray(id)
fun dimenById(id: Int) = AppContext.resources.getDimension(id).toInt()

